﻿using System;
using System.Text.RegularExpressions;
using DBAccessLibrary;
using DBAccessLibrary.Model;

namespace QueryResource.TextFormat
{
    /// <summary>
    /// 将时间字符串 替换成默认格式
    /// </summary>
    internal class DateStatusFormat : ITextFormat
    {

        #region ITextFormat 成员

        public string TextFormat(string sql)
        {
            const string pattern = @"'\d{4}-(1[0-2]|[0]?\d)-(3[01]|[0-2]?\d)[-,\s*](2[0-3]|[0-1]?\d)[.,:]([0-5]\d|[0]?\d)[.,:]([0-5]\d|[0]?\d)'";
            const string datepattern = @"'\d{4}-(1[0-2]|[0]?\d)-(3[01]|[0-2]?\d)'";
            const string db2Pattern = @"timestamp\(" + pattern + @"\)";
            const string db2Datepattern = @"timestamp\(" + datepattern + @"\)";
            const string oraclepattern = @"to_date\(" + pattern + @",'yyyy-mm-dd hh24:mi:ss'\)";
            const string oracledatepattern = @"to_date\(" + datepattern + @",'yyyy-mm-dd hh24:mi:ss'\)";
            //是否是Oracle DateTime格式
            if (Regex.IsMatch(sql, oraclepattern))
            {
                sql = FormatDateReplace(sql, oraclepattern);
            }
            //Oracle Date 格式
            if (Regex.IsMatch(sql, oracledatepattern))
            {
                sql = FormatDateReplace(sql, oracledatepattern);
            }
            //是否是DB2 DateTime格式
            if (Regex.IsMatch(sql, db2Pattern))
            {
                sql = FormatDateReplace(sql, db2Pattern);
            }
            //DB2 Date 格式
            if (Regex.IsMatch(sql, db2Datepattern))
            {
                sql = FormatDateReplace(sql, db2Datepattern);
            }
            //日期
            if (Regex.IsMatch(sql, datepattern))
            {
                sql = FormatDateReplace(sql, datepattern);
            }
            //日期和时间
            if (Regex.IsMatch(sql, pattern))
            {
                sql = FormatDateReplace(sql, pattern, true);
            }
            

            return sql;
        }

        #endregion

        private string FormatDateReplace(string sql, string pattern,bool isTran=false)
        {
            foreach (Match m in Regex.Matches(sql, pattern))
            {
                string text;
                if (m.Value.StartsWith("timestamp", StringComparison.CurrentCultureIgnoreCase))
                {
                    text = m.Value.Remove(0, "timestamp('".Length);
                    text = text.Remove(text.Length - "')".Length);
                }
                else if (m.Value.StartsWith("to_date", StringComparison.CurrentCultureIgnoreCase))
                {
                    text = m.Value.Remove(0, "to_date('".Length);
                    text = text.Remove(text.Length - "','yyyy-mm-dd hh24:mi:ss')".Length);
                }
                else
                {
                    text = m.Value.Remove(0, 1);
                    text = text.Remove(text.Length - 1);
                }

                string[] splits = text.Split(new[] { '-', ' ', '.', ':' }, StringSplitOptions.RemoveEmptyEntries);
                DateTime dt = Convert.ToDateTime(splits.Length == 3 ? string.Format("{0}-{1}-{2}", splits) : string.Format("{0}-{1}-{2} {3}:{4}:{5}", splits));
                string regStr;
                if (isTran)
                {

                    if (SysCache.DBConnection == null)
                    {
                        regStr = Regex.Replace(m.Value, pattern, string.Format("'{0}'", dt.ToString("yyyy-MM-dd-HH.mm.ss")));
                    }
                    else
                    {
                        switch (SysCache.DBConnection.ConnectType)
                        {
                            case DBType.DB2:

                                regStr = Regex.Replace(m.Value, pattern,
                                                       string.Format("timestamp('{0}')",
                                                                     dt.ToString("yyyy-MM-dd-HH.mm.ss")));
                                break;
                            case DBType.Oracle:
                                regStr = Regex.Replace(m.Value, pattern,
                                                       string.Format("to_date('{0}','yyyy-mm-dd hh24:mi:ss')",
                                                                     dt.ToString("yyyy-MM-dd HH:mm:ss")));
                                break;
                            default:
                                regStr = Regex.Replace(m.Value, pattern,
                                                       string.Format("'{0}'", dt.ToString("yyyy-MM-dd HH:mm:ss")));
                                break;
                        }
                    }
                }
                else
                {
                    regStr = Regex.Replace(m.Value, pattern, string.Format("'{0}'", dt.ToString("yyyy-MM-dd HH:mm:ss")));
                }
                sql = sql.Replace(m.Value, regStr);
            }
            return sql;
        }
    }
}
